package com.nd.qa.shareplate.device;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.nd.qa.shareplate.exception.BizException;


/**
 * @修改人：邓风森 @修改时间： 2015/1/16 11:33.
 */
public class CMDUtil {

	public static Map<String, Boolean> runingDevices = new HashMap<String, Boolean>();
	public static List<String> devices;

	/*
	 * @方法描述：执行cmd命令，并回去输出结果
	 *
	 * @参数：cmd 将要执行的命令
	 *
	 * @返回：执行结果
	 *
	 * @修改人：邓风森
	 */
	public static String excuteCMD(String cmd) throws IOException, InterruptedException {
		List<String> result = new ArrayList<String>();
		StringBuffer sBuffer = new StringBuffer();
		System.out.println("CMDUtil--excuteCMD=" + cmd);
		Process process = Runtime.getRuntime().exec(cmd);
		InputStream in = process.getInputStream();
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
		String line;
		while ((line = bufferedReader.readLine()) != null) {
			//result.add(line);
			sBuffer.append(line);
			System.out.println(line);
		}
		in.close();
		bufferedReader.close();
		return sBuffer.toString();
	}

	/**
	 * 获取所有连接在服务器上的设备
	 * 
	 * @return
	 * @throws IOException
	 */
	public static void initDeviceList() throws IOException {
		String cmd = "adb devices";
		devices = new ArrayList<String>();
		String s = null;
		Process process = Runtime.getRuntime().exec(cmd);
		InputStream in = process.getInputStream();
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
		// 跳过第一行
		s = bufferedReader.readLine();
		while ((s = bufferedReader.readLine()) != null) {
			s = s.replace("device", "");
			s = s.trim();
			if (CommonUtils.isNotEmpty(s)) {
				devices.add(s);
			}
		}
		in.close();
		bufferedReader.close();
		process.destroy();
	}

	/**
	 * 获取闲置设备
	 * 
	 * @return
	 */
	public static String getIdleDevice() {
		String idleDeviceName = null;
		for (String device : devices) {
			if (!runingDevices.containsKey(device)) {
				idleDeviceName = device;
				break;
			}
		}
		return idleDeviceName;
	}

	/**
	 * 启用闲置设备，开始测试任务
	 * 
	 * @param s
	 * @throws BizException
	 */
	public static void devicesTesting(String s) throws BizException {
		if (runingDevices.containsKey(s)) {
			throw new BizException("设备已经在工作，无法启用此设备!");
		}
		runingDevices.put(s, true);
	}

	/**
	 * 设备结束测试任务，进入空闲状态
	 * 
	 * @param s
	 */
	public static void deviceEndTest(String s) {
		runingDevices.remove(s);
	}

	public static void main(String[] arg) {

	}
}
